package org.jeecg.modules.basic.entry.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangjiaping on 2021/03/04.
 */
public class WsdlUtil {
    private static String namespace = "http://LwDkService.asmx/";

    /**
     * 访问服务
     * @param url
     * @param method
     * @param params
     * @param result
     * @return
     * @throws Exception
     */
    public static String callService(String url, String method, Map<String, String> params, String result) throws Exception {
        //拼接参数
        String param = getParam(params);
        String soapResponseData = "";
        //拼接SOAP
        StringBuffer soapRequestData = new StringBuffer("");
        soapRequestData.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
        soapRequestData.append("<soap:Body>");
        soapRequestData.append("<" + method + " xmlns=\"" + namespace + "\">");
        soapRequestData.append(param);
        soapRequestData.append("</" + method + ">");
        soapRequestData.append("</soap:Body>" + "</soap:Envelope>");

        PostMethod postMethod = new PostMethod(url);
        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = null;
        InputStream is = null;
        HttpClient httpClient = new HttpClient();
        try {
            b = soapRequestData.toString().getBytes("utf-8");
            is = new ByteArrayInputStream(b, 0, b.length);
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml; charset=UTF-8");
            postMethod.setRequestEntity(re);
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(10000);
            int status = httpClient.executeMethod(postMethod);
            System.out.println("status:" + status);
            System.out.println("retule:" + postMethod.getResponseBodyAsString());
            soapResponseData =  postMethod.getResponseBodyAsString();

           /* if (status == 200) {
                soapResponseData = getMesage(postMethod.getResponseBodyAsString(), result);
            }*/
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return soapResponseData;
    }

    public static String getParam(Map<String, String> params) {
        String param = "";
        if (params != null) {
            Iterator<String> it = params.keySet().iterator();
            while (it.hasNext()) {
                String str = it.next();
                param += "<" + str + ">";
                param += params.get(str);
                param += "</" + str + ">";
            }
        }
        return param;
    }

    public static String getMesage(String soapAttachment, String result) {
        if (result == null) {
            return null;
        }
        if (soapAttachment != null && soapAttachment.length() > 0) {
            int begin = soapAttachment.indexOf(result);
            begin = soapAttachment.indexOf(">", begin);
            int end = soapAttachment.indexOf("</" + result + ">");
            String str = soapAttachment.substring(begin + 1, end);
            str = str.replaceAll("<", "<");
            str = str.replaceAll(">", ">");
            return str;
        } else {
            return "";
        }
    }

    public static String CallWsdl(String serverUrl, Map<String, String> paramsMap) {
        String key;
        String result = "";
        try {
            HttpPost request = new HttpPost(serverUrl);
            List<BasicNameValuePair> params = new ArrayList();
            Iterator<String> it = paramsMap.keySet().iterator();

            while (it.hasNext()) {
                key = it.next();
                params.add(new BasicNameValuePair(key, paramsMap.get(key)));

            }

            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse httpResponse = new DefaultHttpClient().execute(request);
            if (httpResponse.getStatusLine().getStatusCode() != 404) {
                result = EntityUtils.toString(httpResponse.getEntity());
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>00000" + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
